/*PLACEBO TESTS*/

cap program drop runplacebo
program define runplacebo
args controls i j

//preserve data
tempfile backup
save `backup', replace

//Run Placebos
levelsof state_fips, local(stsample)
foreach st of local stsample {
	tempfile placebo`st'
	synth under_100	`controls', trunit(`st') trperiod($tryear) keep(`placebo`st'')
}

//Calculate RMSPE for each placebos
foreach st of local stsample {
	use `placebo`st'', clear
	keep if _time!=.
	gen diff_sq = (_Y_treated- _Y_synthetic)^2
	gen spe_pre = (_Y_treated- _Y_synthetic)^2 if _time <$tryear
	gen denom_pre = 1 if  _time <$tryear
	gen spe_post = (_Y_treated- _Y_synthetic)^2  if _time >= $tryear
	gen denom_post = 1 if _time >= $tryear
	gen att = _Y_treated- _Y_synthetic if _time >= $tryear
	collapse (sum) *_pre *_post (mean) att
	gen rmspe_pre = (spe_pre/denom_pre)^0.5
	gen rmspe_post = (spe_post/denom_post)^0.5
	gen ratio = rmspe_post / rmspe_pre
	gen unit = `st'
	tempfile placebo`st'
	save `placebo`st'', replace
}

//Append all placebos
clear
foreach st of local stsample {
	append using `placebo`st''
}

//Create p-vals
gsort -ratio
gen pval = _n/_N

//Finalize Data and Save
keep if unit==$trfips
keep unit att pval
gen tryear = $tryear
gen model_no = `j'
save "${synth}coef`j'_`i'.dta", replace

//restore data
use `backup', clear

end
